// pages/shopCar/shopCar.js
import api from '../../utils/api.js';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    cartList:[],
    name:"",
    checkedGoodsAmount:Number,
    hasToken:true,
    // 是否单选
    isChecked:Number,
    // 是否全选
    allChecked:false,
    // 购物车件数
    checkedGoodsCount:0

  },
  // 结算
  gotoPay(e){
    if (this.data.checkedGoodsCount!=0){
      let sum = e.currentTarget.dataset.addprice

      wx.navigateTo({
        url: '../beforeOrder/beforeOrder?Price=' + sum,
      })
    }
    else{
      wx.showToast({
        title: '购物车不能为空',
      })
    }
    
  },
  // 全选状态
  seleteAll(){
    console.log(this.data.cartTotal.checkedGoodsCount);
    console.log(this.data.cartTotal.goodsCount)
    let sStr = ""
    if (this.data.cartTotal.checkedGoodsCount == this.data.cartTotal.goodsCount){
      this.setData({
        allChecked
        : false
      })
      console.log(111)
      this.data.cartList.forEach((el,index)=>{
        sStr = sStr + el.product_id+","
      });
      let abc = sStr.slice(0, -1);
      wx.showLoading({
        title: '加载中...',
        mask:true
      })
      wx.request({
        url: api.checked,
        data: {
          productIds: abc,
          isChecked: 0
        },
        header: { 'X-Nideshop-Token': wx.getStorageSync("token").token},
        method: "POST",
        success: res => {
          console.log(res);
          this.setData({
            cartList: res.data.data.cartList,
            cartTotal: res.data.data.cartTotal,
            checkedGoodsAmount: res.data.data.cartTotal.checkedGoodsAmount,
            checkedGoodsCount: res.data.data.cartTotal.checkedGoodsCount
          })
          wx.hideLoading();
        }
      })
    }
    else{
      this.setData({
        allChecked: true
      })
      console.log(2222)
      this.data.cartList.forEach((el, index) => {
        sStr = sStr + el.product_id + ","
      });
      let abc = sStr.slice(0, -1);
      wx.showLoading({
        title: '加载中...',
        mask: true
      })
      wx.request({
        url: api.checked,
        data: {
          productIds: abc,
          isChecked: 1
        },
        header: { 'X-Nideshop-Token': wx.getStorageSync("token").token},
        method: "POST",
        success: res => {
          console.log(res);
          this.setData({
            cartList: res.data.data.cartList,
            cartTotal: res.data.data.cartTotal,
            checkedGoodsAmount: res.data.data.cartTotal.checkedGoodsAmount,
            checkedGoodsCount: res.data.data.cartTotal.checkedGoodsCount
          })
          wx.hideLoading()
        }
      })
    }
  },
  // AJAX
  getData(){
    wx.showLoading({
      title: '加载中...',
      mask: true
    })
    return new Promise((resolve,reject)=>{
      wx.request({
        url: api.shopCar,
        header: { 'X-Nideshop-Token': wx.getStorageSync("token").token },
        success: res => {
          console.log(res)
          let cartTotal = res.data.data.cartTotal
          this.setData({
            cartList: res.data.data.cartList,
            checkedGoodsAmount: res.data.data.cartTotal.checkedGoodsAmount,
            cartTotal,
            checkedGoodsCount: res.data.data.cartTotal.checkedGoodsCount
          })
          console.log(this.data.cartTotal.checkedGoodsCount);
          console.log(this.data.cartTotal.goodsCount);
          // 判断全选
          resolve([this.data.cartTotal.goodsCount, this.data.cartTotal.checkedGoodsCount])
          console.log(this.data.cartList)
          console.log(this.data.cartTotal)
          wx.hideLoading()
        },
        fail: error => {
          console.log(error)
        }
      })
      
    })
  },

  // 选中否
  sel(e){
    console.log(e)
    if (e.currentTarget.dataset.checked==1){
      this.setData({
        isChecked:0
      })
    }
    else{
      this.setData({
        isChecked: 1
      })
    }
    console.log(e)
    wx.request({
      url: api.checked,
      data:{
        productIds: e.currentTarget.dataset.goodid,
        isChecked: this.data.isChecked
      },
      header: { 'X-Nideshop-Token': wx.getStorageSync("token").token },
      method:"POST",
      success:res=>{
        console.log(res);
        this.setData({
          cartList:res.data.data.cartList,
          checkedGoodsAmount: res.data.data.cartTotal.checkedGoodsAmount,
          checkedGoodsCount: res.data.data.cartTotal.checkedGoodsCount
        })
      }
    })
  },

  // 减
  changeDataReduce(e){
    if (e.currentTarget.dataset.number>1){
      e.currentTarget.dataset.number -= 1;
      this.changeData(e)
      console.log(e)
    }
    
  },
  // 加
  changeDataAdd(e){
    if (e.currentTarget.dataset.number<100){
      e.currentTarget.dataset.number += 1;
      console.log(e)
      this.changeData(e)
    }

  },
  // 输入
  inputChange(e){
    // console.log(e)
    let num = Number(e.detail.value);
    if(num>0&&num<101){
      e.currentTarget.dataset.number = num;
    }
    else{
      let index = e.currentTarget.dataset.index;
      console.log(this.data.cartList[index])
      this.data.cartList[index].number = 1;
    }
    
    this.changeData(e)
    // console.log(e.currentTarget.dataset.number)
  },
  // 购物车商品删除
  delShopCarGood(e){
    // console.log(e.currentTarget.dataset.productid)
    let productId = e.currentTarget.dataset.productid;
    console.log(productId)
    wx.request({
      url: api.deleteShopCarData,
      data:{
        productIds: productId+""
      },
      header: { 'X-Nideshop-Token': wx.getStorageSync("token").token },
      method:"POST",
      success:res=>{
        console.log(res)
        this.setData({
          cartList: res.data.data.cartList,
          checkedGoodsAmount: res.data.data.cartTotal.checkedGoodsAmount
        })
      }
    })
  },


  // AJAX
  changeData(params){

    console.log(params)
    let {
      carid: id,
      goodid: goodsId,
      number,
      product_id: productId
    } = params.currentTarget.dataset;
    wx.request({
      url: api.updateCar,
      data:{
        id,
        goodsId,
        number,
        productId
      },
      header: { 'X-Nideshop-Token': wx.getStorageSync("token").token },
      method:"POST",
      success:res=>{
        console.log(res);
        this.setData({
          cartList: res.data.data.cartList,
          checkedGoodsAmount: res.data.data.cartTotal.checkedGoodsAmount,
          checkedGoodsCount: res.data.data.cartTotal.checkedGoodsCount
        })
      }
    })
  },

  gotoLogin(){
    wx.navigateTo({
        url: '../login/login',
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // 判断是否已经登录
    wx.getSetting({
      success: res => {
        console.log(res)
        if (res.authSetting["scope.userInfo"]) {
          console.log("已经授权")
          this.setData({
            hasToken: false
          })
        }
        else {
          console.log("未授权")
          this.setData({
            hasToken: true
          })
          
        }
      }
    })
    // 获取数据,后判断是否全选
    this.getData().then(res=>{
      console.log(res)
      if (res[0] == res[1]) {
        this.setData({
          allChecked:true
        })
      }
    });
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})